package com.news.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.news.dao.UserDao;
import org.news.dao.impl.UserDaoImpl;
import org.news.entity.User;
//处理AJAX登录
@WebServlet(name="login2",urlPatterns="/loginJson")
public class LoginServletJSON  extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		req.setCharacterEncoding("utf-8");
		String uname = req.getParameter("uname");
		String upwd = req.getParameter("upwd");
		System.out.println(uname+"==="+upwd);
		UserDao dao = new UserDaoImpl();
		User user = dao.findUser(uname, upwd);
		if(user!=null){
			//返回json格式的数据(字符串)
			//var o={"name":"电视","price":"5500"}; 
			StringBuffer buffer = new StringBuffer("{");
			buffer.append("\"uid\":\""+user.getUid()+"\"");
			buffer.append(",");
			buffer.append("\"uname\":\""+user.getUname()+"\"");
			buffer.append(",");
			buffer.append("\"upwd\":\""+user.getUpwd()+"\"");
			buffer.append("}");
			out.print(buffer.toString());
		}else{
			out.print("login_error");
		}
		out.close();
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
